<?php

namespace WebmanGrpc\Examples;

use WebmanGrpc\BaseService;

/**
 * 示例gRPC服务
 * 
 * 这是一个示例服务，展示如何创建gRPC服务
 * 注意：实际使用时需要替换为真实的Proto生成的类
 */
class ExampleService extends BaseService
{
    /**
     * 示例方法：简单调用
     * 
     * @param \Google\Protobuf\Internal\Message $request 请求消息
     * @return \Google\Protobuf\Internal\Message 响应消息
     */
    public function SimpleMethod(\Google\Protobuf\Internal\Message $request): \Google\Protobuf\Internal\Message
    {
        // 创建响应消息
        $response = new class extends \Google\Protobuf\Internal\Message {
            protected $message;
            
            public function setMessage($message) {
                $this->message = $message;
            }
            
            public function getMessage() {
                return $this->message;
            }
        };
        
        // 处理请求并设置响应
        $name = $request->getName() ?? 'World';
        $response->setMessage("Hello, {$name}!");
        
        return $response;
    }
    
    /**
     * 示例方法：流式响应
     * 
     * @param \Google\Protobuf\Internal\Message $request 请求消息
     * @return \Generator 响应流
     */
    public function StreamMethod(\Google\Protobuf\Internal\Message $request): \Generator
    {
        $name = $request->getName() ?? 'World';
        
        // 生成多个响应
        for ($i = 1; $i <= 3; $i++) {
            $response = new class extends \Google\Protobuf\Internal\Message {
                protected $message;
                
                public function setMessage($message) {
                    $this->message = $message;
                }
                
                public function getMessage() {
                    return $this->message;
                }
            };
            
            $response->setMessage("Hello, {$name}! (Message {$i})");
            
            // 返回响应并等待下一次迭代
            yield $response;
            
            // 模拟延迟
            usleep(100000); // 0.1秒
        }
    }
    
    /**
     * 示例方法：双向流
     * 
     * @param \Generator $requestStream 请求流
     * @return \Generator 响应流
     */
    public function BidirectionalStream(\Generator $requestStream): \Generator
    {
        // 处理请求流中的每个请求
        foreach ($requestStream as $request) {
            $name = $request->getName() ?? 'World';
            
            // 创建响应
            $response = new class extends \Google\Protobuf\Internal\Message {
                protected $message;
                
                public function setMessage($message) {
                    $this->message = $message;
                }
                
                public function getMessage() {
                    return $this->message;
                }
            };
            
            $response->setMessage("You said: {$name}");
            
            // 返回响应
            yield $response;
        }
    }
}